<template>
  <div>
    <n-menu :mode="mode" :options="menuOptions"></n-menu>
  </div>
</template>

<script setup lang="ts">
import {h, onMounted, ref} from "vue";
import {RouterLink, useRouter} from "vue-router";
import {storeToRefs} from "pinia";
import { useUserStore} from "@/store/module/user";

defineProps({
  mode: {
    type: String,
    default: 'horizontal'
  }
})
const {userInfo} = storeToRefs(useUserStore())
const router = useRouter()
const menuOptions = ref()

onMounted(() => {
  let tree = handleRoutes(router.options.routes)
  menuOptions.value = handleTree(tree)
})

function handleRoutes(routes: any) {
  let tree: any[] = []
  routes.forEach((route: any) => {
    const node = {...route};
    if (route.children && route.children.length > 0) {
      node.children = handleRoutes(route.children);  // 递归处理子路由
    }
    if (route.meta && route.meta.isMenu) {
      tree.push(node);
      if (route.meta.role === '管理员' && userInfo.value.role !== '管理员') {
        tree.pop()
      }
    } else if (route.meta && !route.meta.isMenu) {
      tree = tree.concat(node.children || []);
    }
  });
  return tree;
}

function handleTree(tree: any) {
  let menu: any[] = []
  tree.forEach((item: any) => {
    const node = {...item};
    let option:any = {
      label: () =>
          h(
              RouterLink,
              {
                to: {
                  name: node.name,
                }
              },
              {default: () => node.meta.title}
          ),
      key: node.name,
      children: undefined
    }
    if (item.children && item.children.length > 0) {
      option.children = handleTree(item.children)
    }
    menu.push(option)
  })
  return menu as any[]
}


</script>

<style scoped>

</style>